﻿using UnityEngine;

public class AIRandMove : MonoBehaviour
{
    private Vector3 initialPosition;

    private float _speed_x;
    private float _speed_y;

    private float maxPos_x;
    private float minPos_x;
    private float maxPos_y;
    private float minPos_y;

    private float _timeInterval = 2.5f;
    private float _time;

    private void Awake()
    {
        initialPosition = transform.localPosition;

        maxPos_x = initialPosition.x + 0.5f;
        minPos_x = initialPosition.x - 0.5f;
        maxPos_y = initialPosition.y + 0.5f;
        minPos_y = initialPosition.y - 0.5f;
    }

    private void Start()
    {
        Change();

    }

    private void Update()
    {
        _time += Time.deltaTime;
        if (_time > _timeInterval)
        {
            _time = 0;
            Change();
        }

        transform.Translate(_speed_x, _speed_y, 0, Space.Self);
        Check();
    }

    private void Change()
    {
        _speed_x = Random.Range(0.01f, 0.05f);
        _speed_y = Random.Range(0.01f, 0.05f);
    }

    private void Check()
    {
        // 如果到达预设的界限位置值，调换速度方向并让它当前的坐标位置等于这个临界边的位置值
        if (transform.localPosition.x > maxPos_x)
        {
            _speed_x = -_speed_x;
            transform.localPosition = new Vector3(maxPos_x, transform.localPosition.y, initialPosition.z);
        }
        if (transform.localPosition.x < minPos_x)
        {
            _speed_x = -_speed_x;
            transform.localPosition = new Vector3(minPos_x, transform.localPosition.y, initialPosition.z);
        }
        if (transform.localPosition.y > maxPos_y)
        {
            _speed_y = -_speed_y;
            transform.localPosition = new Vector3(transform.localPosition.x, maxPos_y, initialPosition.z);
        }
        if (transform.localPosition.y < minPos_y)
        {
            _speed_y = -_speed_y;
            transform.localPosition = new Vector3(transform.localPosition.x, minPos_y, initialPosition.z);
        }
    }
}